import { faker } from '@faker-js/faker';
import { getMenuIds, MOCK_MENU_LIST } from '~/utils/mock-data';
import type { PagedList } from '~/utils/types';
import { createSuccessResponse } from '~/utils/response';

const formatterCN = new Intl.DateTimeFormat('zh-CN', {
  timeZone: 'Asia/Shanghai',
  year: 'numeric',
  month: '2-digit',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
});

const menuIds = getMenuIds(MOCK_MENU_LIST);

interface RoleDto {
  id: string;
  name: string;
  status: number;
  createTime: string;
  permissions: string[];
  remark?: string;
}

function generateMockDataList(count: number): RoleDto[] {
  const dataList: RoleDto[] = [];

  for (let i = 0; i < count; i++) {
    const dataItem: RoleDto = {
      id: faker.string.uuid(),
      name: faker.commerce.product(),
      status: faker.helpers.arrayElement([0, 1]),
      createTime: formatterCN.format(
        faker.date.between({ from: '2022-01-01', to: '2025-01-01' }),
      ),
      permissions: faker.helpers.arrayElements(menuIds).map(String),
      remark: faker.lorem.sentence(),
    };

    dataList.push(dataItem);
  }

  return dataList;
}

const mockData = generateMockDataList(100);

export default eventHandler(async (event) => {
  const {
    pageNumber = 1,
    pageSize = 20,
    name,
    id,
    remark,
    startTime,
    endTime,
    status,
    orderBy,
    isDesc,
  } = getQuery(event);

  let listData = structuredClone(mockData);

  // 应用筛选条件
  if (name) {
    listData = listData.filter((item) =>
      item.name.toLowerCase().includes(String(name).toLowerCase()),
    );
  }
  if (id) {
    listData = listData.filter((item) =>
      item.id.toLowerCase().includes(String(id).toLowerCase()),
    );
  }
  if (remark) {
    listData = listData.filter((item) =>
      item.remark?.toLowerCase()?.includes(String(remark).toLowerCase()),
    );
  }
  if (startTime) {
    listData = listData.filter((item) => item.createTime >= String(startTime));
  }
  if (endTime) {
    listData = listData.filter((item) => item.createTime <= String(endTime));
  }
  if (['0', '1'].includes(status as string)) {
    listData = listData.filter((item) => item.status === Number(status));
  }

  // 计算分页数据
  const totalCount = listData.length;
  const currentPage = Number(pageNumber);
  const itemsPerPage = Number(pageSize);
  const totalPages = Math.ceil(totalCount / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;

  // 排序处理
  if (orderBy && typeof orderBy === 'string') {
    const sortOrder = isDesc ? -1 : 1;
    listData.sort((a, b) => {
      const aValue = a[orderBy as keyof RoleDto];
      const bValue = b[orderBy as keyof RoleDto];
      if (aValue < bValue) return -1 * sortOrder;
      if (aValue > bValue) return 1 * sortOrder;
      return 0;
    });
  }

  // 构造分页响应
  const pagedData: PagedList<RoleDto> = {
    items: listData.slice(startIndex, endIndex),
    totalCount,
    pageNumber: currentPage,
    pageSize: itemsPerPage,
    totalPages,
    hasPreviousPage: currentPage > 1,
    hasNextPage: currentPage < totalPages
  };

  return createSuccessResponse(pagedData, '获取角色列表成功');
});
